package com.cuihom.servicezuuldemo.com.cuihom.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cuixing
 * @package com.cuihom.servicezuuldemo.com.cuihom.filter
 * @class MyFilter
 * @email xing.cui@magicwindow.cn
 * @date 2018/5/29 下午6:59
 * @description
 */

@Component
public class MyPreFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyPreFilter.class);


    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null){
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try{
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){

            }
        }
        log.info("ok");
        return null;
    }
}